package com.franz.noteapp.compose.showNotes.compose

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.animation.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Sort
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.core.graphics.ColorUtils
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import com.franz.noteapp.bean.NoteBean
import com.franz.noteapp.bean.NoteType
import com.franz.noteapp.compose.showNotes.NotesEvent
import com.franz.noteapp.compose.showNotes.NotesViewModel
import com.franz.noteapp.nav.NavigationItem
import com.franz.noteapp.ui.theme.NoteTheme
import kotlinx.coroutines.launch

/**
 * 展示所有创建的笔记*/
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun ShowNotePage(navController: NavController,viewModel: NotesViewModel = hiltViewModel()){
    val state = viewModel.state.value
    val scaffoldState = rememberScaffoldState()
    val scope = rememberCoroutineScope()
    Scaffold(
        floatingActionButton = {
            FloatingActionButton(
                backgroundColor = NoteTheme.colors.primary,
                /**
                 * 跳转创建笔记页面，因为是创建不需要传递参数，采用默认值*/
                onClick = { navController.navigate(NavigationItem.EditNote.route) }
            ) {
                Icon(imageVector = Icons.Default.Add, contentDescription = "创建新笔记")
            }
        },
        scaffoldState = scaffoldState
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(NoteTheme.colors.background)
                .padding(top = 45.dp, start = 10.dp, end = 10.dp, bottom = 10.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth().padding(top = 10.dp)
            ) {
                Text(text = "NoteApp", style = MaterialTheme.typography.h4, color = NoteTheme.colors.primary)
                Spacer(modifier = Modifier.weight(1f))
                Icon(
                    imageVector = Icons.Default.Sort,
                    contentDescription = "排序",
                    tint = NoteTheme.colors.primary,
                    modifier = Modifier.clickable {
                        viewModel.onEvent(NotesEvent.ToggleOrderSection)
                    }
                )
            }

            /**
             * 笔记排序组件是否显示*/
            AnimatedVisibility(
                visible = state.isOrderSectionVisible,
                enter = fadeIn() + slideInVertically(),
                exit = fadeOut() + slideOutVertically()
            ) {
                OrderSelect(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 16.dp),
                    noteType = state.noteType)
                {
                    viewModel.onEvent(NotesEvent.Type(it))
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            /**
             * 笔记列表*/
            NoteList(navController,notes = state.notes){
                //笔记删除事件
                viewModel.onEvent(NotesEvent.Delete(it))
                scope.launch {
                    val result = scaffoldState.snackbarHostState.showSnackbar(
                        message = "笔记已删除",
                        actionLabel = "撤回")
                    if (result == SnackbarResult.ActionPerformed){
                        viewModel.onEvent(NotesEvent.RestoreNote)
                    }
                }
            }
        }
    }
}

/**
 * 笔记列表*/
@Composable
fun NoteList(navController: NavController,notes:List<NoteBean>, onDeleteClick: (NoteBean) -> Unit){
    LazyColumn(modifier = Modifier.fillMaxSize()){
        items(notes.size){
            NoteItem(bean = notes[it], onDeleteClick = { onDeleteClick(notes[it])}, modifier = Modifier.fillMaxWidth().wrapContentHeight().clickable {
                ///跳转笔记编辑界面
                navController.navigate(NavigationItem.EditNote.route+"?noteId=${notes[it].id}&noteColor=${notes[it].color}")
            })
            if (it < notes.size - 1){
                Spacer(modifier = Modifier.height(16.dp))
            }
        }
    }
}

/**
 * 单个笔记*/
@Composable
fun NoteItem(
    bean: NoteBean,
    modifier: Modifier = Modifier,
    cornerRadius: Dp = 10.dp,
    cutCornerSize: Dp = 30.dp,
    onDeleteClick: () -> Unit)
{
    Box(modifier = modifier){
        Canvas(modifier = Modifier.matchParentSize()){
            /**
             * 绘制笔记路径*/
            val clipPath = Path().apply {
                lineTo(size.width - cutCornerSize.toPx(), 0f)//上
                lineTo(size.width, cutCornerSize.toPx())//右
                lineTo(size.width, size.height)//下
                lineTo(0f, size.height)//左
                close()
            }

            /**
             * 对右上角圆角进行折叠处理*/
            clipPath(clipPath) {
                drawRoundRect(
                    color = Color(bean.color),
                    size = size,
                    cornerRadius = CornerRadius(cornerRadius.toPx())
                )
                drawRoundRect(
                    color = Color(
                        ColorUtils.blendARGB(bean.color, 0x000000, 0.2f)
                    ),
                    topLeft = Offset(size.width - cutCornerSize.toPx(), -100f),
                    size = Size(cutCornerSize.toPx() + 100f, cutCornerSize.toPx() + 100f),
                    cornerRadius = CornerRadius(cornerRadius.toPx())
                )
            }
        }

        Column(
            modifier = Modifier
             .fillMaxSize()
             .padding(top = 16.dp, start = 16.dp, bottom = 16.dp,end = 32.dp),
            verticalArrangement = Arrangement.Center
        )
        {
            Text(
                text = bean.title,
                style = MaterialTheme.typography.h6,
                color = MaterialTheme.colors.onSurface,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = bean.content,
                style = MaterialTheme.typography.body1,
                color = MaterialTheme.colors.onSurface,
                maxLines = 10,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.fillMaxWidth()
            )
        }

        Icon(
            imageVector = Icons.Default.Delete,
            contentDescription = "删除",
            tint = NoteTheme.colors.onSurface,
            modifier = Modifier
                .align(Alignment.BottomEnd)
                .padding(8.dp)
                .clickable {
                    onDeleteClick()
                }
        )

    }
}